<template>
  <div class="upload-container">
    <div style="text-align: center">
      <el-upload
        ref="cardIDFront"
        :data="dataObj"
        :multiple="false"
        :limit="limit"
        :file-list="fileList"
        :before-upload="beforeAvatarUpload"
        :on-success="handleImgUploadChange.bind(this,'front')"
        :on-remove="handleImageRemove"
        class="image-uploader"
        drag
        :action="baseUrl + 'api/v1/upload/file'"
      >
        <div v-if="!idcard || !idcardPath.front">
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ idcard ? "将身份证正面照片(人像面)" : "将文件" }}拖到此处，或<em
              >点击上传</em
            >
          </div>
        </div>

        <div v-if="idcardPath.front">
          <img style="width: 100%" :src="idcardPath.front" alt="" />
        </div>
      </el-upload>
      <el-upload
        ref="back"
        v-if="idcard"
        :data="dataObjback"
        :multiple="false"
        :before-upload="beforeAvatarUpload"
        :on-success="handleImgUploadChange.bind(this,'back')"
        class="image-uploader"
        drag
        :action="baseUrl + 'api/v1/upload/file'"
      >
        <div v-if="!idcardPath.back">
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将身份证反面照片(国徽面)拖到此处，或<em>点击上传</em>
          </div>
        </div>

        <div v-if="idcardPath.back">
          <img style="width: 100%" :src="idcardPath.back" alt="" />
        </div>
      </el-upload>
    </div>

    <div v-if="idcard && (idcardDataFront.name || idcardDataBack.valid_to)">
      <el-descriptions class="margin-top" title="" :column="3" border>
        <el-descriptions-item label="姓名">{{
          idcardDataFront.name
        }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{
          idcardDataFront.number
        }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{
          idcardDataFront.sex
        }}</el-descriptions-item>
        <el-descriptions-item label="民族">{{
          idcardDataFront.ethnicity
        }}</el-descriptions-item>
        <el-descriptions-item label="生日">{{
          idcardDataFront.birth
        }}</el-descriptions-item>
        <el-descriptions-item label="办理时间">{{
          idcardDataBack.valid_from
        }}</el-descriptions-item>
        <el-descriptions-item label="到期时间">{{
          idcardDataBack.valid_to
        }}</el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/api/qiniu";

export default {
  name: "SingleImageUpload",
  props: {
    value: {
      type: String,
      default: "",
    },
    idcard: {
      type: Boolean,
      default: false,
    },
    idcardType: {
      type: String,
      default: "front",
    },
    allowFile:{
      type:Boolean,
      default:false
    },
    limit:{
      type:Number,
      default:1
    }
  },
  data() {
    return {
      tempUrl: "",
      dataObj: { folder: "test" },
      dataObjback: {
        folder: "oa-idcard",
        type: "idcard",
        idcardType: "back",
        analysis: true,
      },
      baseUrl: "",
      idcardDataFront: {},
      idcardDataBack: {},
      idcardPath: {},
      fileList:[]
    };
  },
  computed: {
    imageUrl() {
      return this.value;
    },
  },
  created() {
    this.baseUrl = process.env.VUE_APP_UPLOAD;
  },
  mounted() {
    if (this.idcard) {
      this.dataObj = {
        folder: "oa-idcard",
        type: "idcard",
        idcardType: "front",
        analysis: true,
      };
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 <= 2;
      if (!this.allowFile && !isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG 或 PNG 格式!");
        return false
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return false
      }

      return true
    },
    rmImage() {
      this.emitInput("");
    },
    emitInput(val) {
      this.$emit("input", val);
    },
    // handleImageSuccess(res) {
    //   console.log(this.idcard,'idcard');
    //   if (res.code == 200) {
    //     if (this.idcard) {
    //       if (res.data.analysis.error_code) {
    //         this.$refs.cardIDFront.clearFiles();
    //         this.$message({
    //           message: "识别失败，请重新上传！",
    //           type: "error",
    //         });
    //       } else {
    //         this.idcardDataFront = res.data.analysis.result;
    //         this.idcardPath.front = res.data.path;
    //         this.$emit("input", res.data, "front");
    //         this.$message({
    //           message: "识别成功",
    //           type: "success",
    //         });
    //       }
    //     } else {
    //       this.$emit("input", res.data);
    //       this.$message({
    //         message: "上传成功",
    //         type: "success",
    //       });
    //     }
    //   }
    // },
    // handleImageBackSuccess(res) {
    //   if (res.code == 200) {
    //     if (res.data.analysis.error_code) {
    //       this.$refs.back.clearFiles();
    //       this.$message({
    //         message: "识别失败，请重新上传！",
    //         type: "error",
    //       });
    //     } else {
    //       this.$message({
    //         message: "识别成功",
    //         type: "success",
    //       });
    //       this.idcardDataBack = res.data.analysis.result;
    //       this.idcardPath.back = res.data.path;
    //       this.$emit("input", res.data, "back");
    //     }
    //   }
    // },
    beforeUpload() {
      const _self = this;
      return new Promise((resolve, reject) => {
        getToken()
          .then((response) => {
            const key = response.data.qiniu_key;
            const token = response.data.qiniu_token;
            _self._data.dataObj.token = token;
            _self._data.dataObj.key = key;
            this.tempUrl = response.data.qiniu_url;
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    handleImageRemove(file){
      console.log(file,'file');
      this.$emit("remove")
    },
    async handleImgUploadChange(isFront,res){
      const {data}=res
      try {
        if (this.idcard) {
          const {analysis:{error_code,result},path}=data
          if (error_code) {
            isFront==='front'?this.$refs.cardIDFront.clearFiles():this.$refs.back.clearFiles()
            this.$message.error("识别失败,请重新上传")
          }else {
            if (isFront==='front') {
              this.idcardDataFront=result
              this.idcardPath.front=path
            } else {
              this.idcardDataBack=result
              this.idcardPath.back=path
            }
            this.$emit("input", data, isFront);
            this.$message.success("识别成功")
          }
        }else {
          this.$emit("input", data);
          this.$message.success("上传成功")
        }
      } catch (error) {
        console.log(error,'error');
        this.$message.error("上传失败")
      }
    }
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.upload-container {
  width: 100%;
  position: relative;
  @include clearfix;

  .image-uploader {
    width: 50%;
    float: left;
  }

  .image-preview {
    width: 200px;
    height: 200px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;

    .image-preview-wrapper {
      position: relative;
      width: 100%;
      height: 100%;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .image-preview-action {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, 0.5);
      transition: opacity 0.3s;
      cursor: pointer;
      text-align: center;
      line-height: 200px;

      .el-icon-delete {
        font-size: 36px;
      }
    }

    &:hover {
      .image-preview-action {
        opacity: 1;
      }
    }
  }
}
</style>
